<script setup lang="ts">
import { ref } from 'vue'
import Test_title from '@/components/Test_title.vue'
import router from '@/router'
import { userGetPaperListService, userGetScoreService } from '@/api/user'
import { Reading } from '@element-plus/icons-vue'

const test_title = ref([
  {
    id: 1,
    title: '测试1',
    publisher: '胡清钟',
    testTime: 40,
    status: 1,
    beginTime: '2024-12-10',
    endTime: '2024-12-10'
  },
  {
    id: 2,
    title: '测试2',
    publisher: '胡清钟',
    testTime: 10,
    status: 2
  }
])

// 定义 status 枚举
enum Status {
  InProgress = 1,
  Completed = 2,
  Ended = 3
}

const formData = ref({
  currentPage: 1,
  pageSize: 10,
  searchContent: '',
  status: '全部'
})

const totalPage = ref()

// 计算属性，基于 status 返回标签内容和类型
const statusTag = (status: number) => {
  switch (status) {
    case Status.InProgress:
      return { label: '进行中', type: 'primary' }
    case Status.Completed:
      return { label: '已完成', type: 'success' }
    case Status.Ended:
      return { label: '已结束', type: 'danger' }
    default:
      return { label: '未知状态', type: 'info' }
  }
}

let testRule = ref(false)

let currentTest = ref()

const getPaperList = async () => {
  const res = await userGetPaperListService(formData.value)
  console.log(res.data.data)

  // 获取试卷列表
  test_title.value = res.data.data.records

  // 使用 Promise.all 并发调用 `userGetScoreService`
  // 更新试卷列表
  test_title.value = await Promise.all(
    test_title.value.map(async (item) => {
      const hasScore = await userGetScoreService(item.id)
      console.log('itemId:' + item.id + 'hasScore:' + hasScore.data.data)
      if (hasScore.data.data && item.status === 1) {
        item.status = 2 // 更新状态为 2
      }
      return item // 返回更新后的对象
    })
  )
}

getPaperList()

const startTest = (item: object) => {
  if(item.status === 2){
    ElMessage.success('考试已完成，请等待考试结束公布成绩')
    return
  }
  if (item.status === 3) {
    router.push(`/student/test/result/${item.id}`)
  } else {
    testRule.value = ref(true)
    currentTest.value = item
    startCountdown()
  }
}

const checkTest = (id: number) => {
  router.push(`/student/test/${id}`)
}

const countdown = ref(5)
const startCountdown = () => {
  const interval = setInterval(() => {
    if (countdown.value === 0) {
      clearInterval(interval)
    } else {
      countdown.value--
    }
  }, 1000)
}
</script>

<template>
  <div id="main-stuTestPage">
    <div class="search-area">
      <el-input
        placeholder="请输入试卷名称"
        style="width: 250px; margin-left: 20px"
        v-model="formData.searchContent"
      ></el-input>
      <el-button type="primary" @click="getPaperList">搜索</el-button>
      <el-select style="width: 200px" v-model="formData.status" placeholder="请选择状态">
        <el-option value="全部">全部</el-option>
        <el-option value="进行中">进行中</el-option>
        <el-option value="已截止">已截止</el-option>
      </el-select>
    </div>
    <el-scrollbar style="margin-top: 20px" height="70vh">
      <Test_title v-for="item in test_title" :key="item.id">
        <template #status>
          <el-tag :type="statusTag(item.status).type">{{ statusTag(item.status).label }}</el-tag>
        </template>
        <template #title>{{ item.title }}</template>
        <template #publisher>{{ item.publisher }}</template>
        <template #testTime>{{ item.testTime != 0 ? item.testTime + '分钟' : '不限时' }}</template>
        <template #duration>{{ item.beginTime }} 至 {{ item.endTime }}</template>
        <template #check>
          <el-icon class="delete-icon" @click="startTest(item)" style="font-size: 30px">
            <Reading />
          </el-icon>
          <a @click="startTest(item)">查看测试</a>
        </template>
      </Test_title>
    </el-scrollbar>
    <div class="pagination-area">
      <el-pagination
        v-model:current-page="formData.currentPage"
        background
        layout="prev, pager, next"
        :total="totalPage"
        @current-change="getPaperList"
      />
    </div>
  </div>

  <el-dialog v-model="testRule" append-to-body="true" title="考试守则" width="600" center>
    <div class="test-rule">
      考试时间：{{ currentTest.testTime != 0 ? currentTest.testTime + '分钟' : '不限时' }}
      <p>1.确保设备正常，网络稳定，浏览器和相关插件已更新。</p>
      <p>2.禁止与他人共享设备或借用他人设备。</p>
      <p>3.考生必须独立作答，不得借助外部工具或与他人交流。</p>
      <p>4.考试时间到后，系统将自动提交答卷。</p>
      <p>5.确认答案已提交完毕，不得再进行修改。</p>
      <el-button type="primary" disabled v-if="countdown > 0">{{ countdown }}秒后开始</el-button>
      <el-button type="primary" v-if="countdown === 0" @click="checkTest(currentTest.id)"
        >开始考试
      </el-button>
      <el-button type="warning" @click="testRule = false">取消</el-button>
    </div>
  </el-dialog>
</template>

<style scoped>
#main-stuTestPage {
  padding: 10px;
}

.test-rule {
  line-height: 2.5rem;
}

.search-area {
  width: 600px;
  display: flex;
  justify-content: space-between;
}

.pagination-area {
  height: 50px;
  width: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
}

.delete-icon:hover {
  color: skyblue;
}
</style>
